package www.yingdi365.com.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpHeaders;
import com.zhy.magicviewpager.transformer.ScaleInTransformer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;
import www.yingdi365.com.R;
import www.yingdi365.com.base.ZjbBaseNotLeftActivity;
import www.yingdi365.com.constant.Constant;
import www.yingdi365.com.fragment.ZaZhiBJYLFragment;
import www.yingdi365.com.model.AppMagazine;
import www.yingdi365.com.model.AppMagazineSave;
import www.yingdi365.com.model.AppMagazineSaveResult;
import www.yingdi365.com.model.AppMusic;
import www.yingdi365.com.model.OkObject;
import www.yingdi365.com.model.QingJianBean;
import www.yingdi365.com.model.ZaZhi;
import www.yingdi365.com.util.DpUtils;
import www.yingdi365.com.util.GsonUtils;
import www.yingdi365.com.util.LogUtil;
import www.yingdi365.com.util.ScreenUtils;

public class BianJiZZYLActivity extends ZjbBaseNotLeftActivity implements View.OnClickListener {
    private ViewPager id_viewpager;
    private TextView textViewRight;
    private String id;
    private List<QingJianBean> qingJianBeanList = new ArrayList<>();
    public AppMagazine appMagazine;
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case Constant.BROADCASTCODE.QingJianBaoCun:
                    int positionGG = intent.getIntExtra(Constant.INTENT_KEY.Position, -1);
                    QingJianBean pagesBean = (QingJianBean) intent.getSerializableExtra(Constant.INTENT_KEY.pagesBean);
                    qingJianBeanList.set(positionGG, pagesBean);
                    zaZhi.setPages(qingJianBeanList);
                    LogUtil.LogShitou("BianJiZZYLActivity--编辑后的杂志对象", "" + GsonUtils.parseObject(zaZhi));
                    appMagazine.setRenderData(GsonUtils.parseObject(zaZhi));
                    baoCunQingJian();
                    break;
                case Constant.BROADCASTCODE.XiuGaiYY:
                    AppMusic music = (AppMusic) intent.getSerializableExtra(Constant.INTENT_KEY.music);
                    appMagazine.setMusic(music);
                    baoCunQingJian();
                    break;
                case Constant.BROADCASTCODE.XiuGaiQJSX:
                    String qingJian = intent.getStringExtra(Constant.INTENT_KEY.QingJian);
                    appMagazine.setRenderData(qingJian);
                    initQingJianBeanList();
                    initViewPager();
                    baoCunQingJian();
                    break;
            }
        }

        private OkObject getOkObject1() {
            String url = Constant.HOST + Constant.Url.AppMagazineService + "magazine/save";
            HttpHeaders headers = new HttpHeaders();
            headers.put(Constant.TOKEN, appLoginResult.getToken());
            HashMap<String, String> params = new HashMap<>();
            return new OkObject(headers, params, url);
        }

        private void baoCunQingJian() {
            AppMagazineSave appMagazineSave = new AppMagazineSave(
                    appMagazine.getUuid(),
                    appMagazine.getId(),
                    appMagazine.getMusic(),
                    appMagazine.getName(),
                    appMagazine.getRenderData(),
                    appMagazine.getTmpl());
            LogUtil.LogShitou("BianJiZZYLActivity--杂志保存对象", ""+appMagazine.getRenderData());
            showLoadingDialog();
            OkObject okObject = getOkObject1();
            OkGo.post(okObject.getUrl())//
                    .tag(this)//
                    .headers(okObject.getHeaders())
                    .upJson(GsonUtils.parseObject(appMagazineSave))//
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            cancelLoadingDialog();
                            LogUtil.LogShitou("BianJiZZYLActivity--保存杂志", "" + s);
                            try {
                                AppMagazineSaveResult appMagazineSaveResult = GsonUtils.parseJSON(s, AppMagazineSaveResult.class);
                                if (appMagazineSaveResult.isSuccess()) {
                                    Toast.makeText(BianJiZZYLActivity.this, appMagazineSaveResult.getMessage(), Toast.LENGTH_SHORT).show();
                                } else {
                                    Toast.makeText(BianJiZZYLActivity.this, appMagazineSaveResult.getMessage(), Toast.LENGTH_SHORT).show();
                                }
                            } catch (Exception e) {
                                Toast.makeText(BianJiZZYLActivity.this, getResources().getString(R.string.shujuchucuo), Toast.LENGTH_SHORT).show();
                            }
                        }

                        @Override
                        public void onError(Call call, Response response, Exception e) {
                            super.onError(call, response, e);
                            cancelLoadingDialog();
                            if (response != null) {
                                if (response.code() == 401) {
                                    showReLoginDialog();
                                }
                            }
                            Toast.makeText(BianJiZZYLActivity.this, getResources().getString(R.string.qingqiushibai), Toast.LENGTH_SHORT).show();
                        }
                    });
        }
    };

    private void initViewPager() {
        id_viewpager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
        id_viewpager.setPageMargin((int) DpUtils.convertDpToPixel(20f, BianJiZZYLActivity.this));
        id_viewpager.setOffscreenPageLimit(3);
        id_viewpager.setPageTransformer(true, new ScaleInTransformer());
    }

    private void initQingJianBeanList() {
        zaZhi = GsonUtils.parseJSON(appMagazine.getRenderData(), ZaZhi.class);
        qingJianBeanList.clear();
        qingJianBeanList.addAll(zaZhi.getPages());
    }

    private ZaZhi zaZhi;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bian_ji_zzyl);
        init();
    }

    @Override
    protected void initSP() {

    }

    @Override
    protected void initIntent() {
        Intent intent = getIntent();
        id = intent.getStringExtra(Constant.INTENT_KEY.ID);
    }

    @Override
    protected void findID() {
        id_viewpager = (ViewPager) findViewById(R.id.id_viewpager);
        textViewRight = (TextView) findViewById(R.id.textViewRight);
    }

    @Override
    protected void initViews() {
        ((TextView) findViewById(R.id.textViewTitle)).setText("杂志预览");
        textViewRight.setText("发送杂志");
        int screenWidth = ScreenUtils.getScreenWidth(this);
        ViewGroup.LayoutParams layoutParams = id_viewpager.getLayoutParams();
        float width = screenWidth - DpUtils.convertDpToPixel(100f, this);
        layoutParams.width = (int) width;
        layoutParams.height = (int) (width * 1.4375f);
        id_viewpager.setLayoutParams(layoutParams);
    }

    @Override
    protected void setListeners() {
        findViewById(R.id.imageBack).setOnClickListener(this);
        findViewById(R.id.viewYeMain).setOnClickListener(this);
        findViewById(R.id.viewYinYue).setOnClickListener(this);
        findViewById(R.id.viewYuLan).setOnClickListener(this);
    }

    private OkObject getOkObject() {
        String url = Constant.HOST + Constant.Url.AppMagazineService + "magazine/" + id;
        HttpHeaders headers = new HttpHeaders();
        headers.put(Constant.TOKEN, appLoginResult.getToken());
        HashMap<String, String> params = new HashMap<>();
        return new OkObject(headers, params, url);
    }

    @Override
    protected void initData() {
        showLoadingDialog();
        OkObject okObject = getOkObject();
        OkGo.get(okObject.getUrl())//
                .tag(this)//
                .headers(okObject.getHeaders())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        cancelLoadingDialog();
                        try {
                            appMagazine = GsonUtils.parseJSON(s, AppMagazine.class);
                            initQingJianBeanList();
                            initViewPager();
                        } catch (Exception e) {
                            Toast.makeText(BianJiZZYLActivity.this, getResources().getString(R.string.shujuchucuo), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        cancelLoadingDialog();
                        if (response != null) {
                            if (response.code() == 401) {
                                showReLoginDialog();
                            }
                        }
                        Toast.makeText(BianJiZZYLActivity.this, getResources().getString(R.string.qingqiushibai), Toast.LENGTH_SHORT).show();
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (Constant.REQUEST_RESULT_CODE.XiuGaiQingJian == requestCode && Constant.REQUEST_RESULT_CODE.XiuGaiQingJian == resultCode) {
            initData();
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.viewYuLan:
                intent.setClass(this, WebActivity.class);
                intent.putExtra(Constant.INTENT_KEY.TITLE, "预览");
                intent.putExtra(Constant.INTENT_KEY.URL, appMagazine.getHtmlUrl());
                startActivity(intent);
                break;
            case R.id.viewYinYue:
                intent.setClass(this, SheZhiYYActivity.class);
                intent.putExtra(Constant.INTENT_KEY.appMagazine, appMagazine);
                startActivity(intent);
                break;
            case R.id.viewYeMain:
                intent.setClass(this, YeMainTZActivity.class);
                intent.putExtra(Constant.INTENT_KEY.appMagazine, appMagazine);
                startActivity(intent);
                break;
            case R.id.imageBack:
                finish();
                break;
        }
    }

    class MyPagerAdapter extends FragmentStatePagerAdapter {

        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return new ZaZhiBJYLFragment(qingJianBeanList.get(position), position);
        }

        @Override
        public int getCount() {
            return qingJianBeanList.size();
        }

        @Override
        public int getItemPosition(Object object) {
            return PagerAdapter.POSITION_NONE;
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constant.BROADCASTCODE.QingJianBaoCun);
        filter.addAction(Constant.BROADCASTCODE.XiuGaiQJWZ);
        filter.addAction(Constant.BROADCASTCODE.XiuGaiYY);
        filter.addAction(Constant.BROADCASTCODE.XiuGaiQJSX);
        registerReceiver(receiver, filter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }
}
